import re
from decimal import Decimal

from celery import current_app
from django.contrib.sessions.backends import db
from django.shortcuts import render
from django import http
# Create your views here.
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
import json
from django_redis import get_redis_connection
from datetime import datetime
import logging

from apps import houses
from apps.houses.models import House
from apps.orders.models import Order
from apps.orders.utils import check_order
from apps.users.models import User

logger = logging.getLogger('django')


# 添加订单
class AddOrder(LoginRequiredMixin, View):
    """实现房屋订单功能"""

    # 添加订单  POST　/api/v1.0/orders
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')

        # 校验参数
        if not all([house_id, start_date, end_date]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断house_id是否合法
        # 校验时间格式
        if not re.match(r"(\d{4}-\d{1,2}-\d{1,2})", start_date):
            return http.JsonResponse({'code': 400, 'errmsg': '参数date有误'})
        if not re.match(r"(\d{4}-\d{1,2}-\d{1,2})", end_date):
            return http.JsonResponse({'code': 400, 'errmsg': '参数date有误'})
        # fmt = '%Y-%m-%d'
        # start_day = datetime.strptime(str(start_date), fmt).date()
        # end_day = datetime.strptime(str(end_date), fmt).date()

        if start_date >= end_date:
            return http.JsonResponse({'code': 400, 'errmsg': '参数date有误'})
        try:
            house = House.objects.get(id=house_id)
        except Exception:
            return http.HttpResponseForbidden('参数house_id错误')

        user = request.user
        # user.自定义外键名 当前用户是否操作自己房子
        if house.user == user:
            return http.JsonResponse({'code': 4003, 'errmsg': '不能操作自己房子'})

        # 判断房屋是否被预定
        ret = check_order(house, start_date, end_date)
        if not ret:
            return http.JsonResponse({"errno": 4003, "errmsg": "已被预定"})
        fmt = '%Y-%m-%d'
        start_day = datetime.strptime(str(start_date), fmt).date()
        end_day = datetime.strptime(str(end_date), fmt).date()
        days = (end_day - start_day).days
        order = Order.objects.create(
            user=user,
            house=house,
            begin_date=start_day,
            end_date=end_day,
            days=days,
            house_price=Decimal(house.price),
            amount=days * Decimal(house.price),
        )

        data = {"order_id": order.id}
        return http.JsonResponse({"data": data, "errno": "0", "errmsg": "下单成功"})

    def get(self, request):
        role = request.GET.get('role')
        if not role:
            return http.JsonResponse({'code': 400, 'errmsg': '参数有误'})
        user = request.user
        if role == 'custom':
            orders = Order.objects.filter(user=user).all()
        elif role == 'landlord':
            # role == 'landlord':如果用户是房东,查询属于自己的房子
            houses = House.objects.filter(user=user).all()
            # 再查询预定了自己房子的订单
            orders = Order.objects.filter(house__in=houses).all()
        else:
            return http.JsonResponse({"errno": "4001", "errmsg": "该操作不存在"})

        order_list = []
        for order in orders:
            order_list.append({
                "amount": order.amount,
                "comment": order.comment,
                "ctime": order.create_time,
                "days": order.days,
                "end_date": order.end_date,
                "img_url": order.house.index_image_url,
                "order_id": order.id,
                "start_date": order.begin_date,
                "status": Order.ORDER_STATUS_ENUM[order.status],
                "title": order.house.title
            })
        data = {"orders": order_list}
        return http.JsonResponse({"data": data, "errno": "0", "errmsg": "查询成功"})
    #
    # def put(self):
    #     """实现订单接单或拒绝逻辑以及评价逻辑"""
    #
    #     pass
    #
    # def put1(self):
    #     """实现订单接单或拒绝逻辑以及评价逻辑"""
    #
    #     pass


class AcceptOrder(LoginRequiredMixin, View):
    # PUT /api/v1.0/orders/[int:order_id]/status
    # 房东:接单,拒单
    def put(self, request, order_id):
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        reason = json_dict.get('reason')

        if not action:
            return http.JsonResponse({"errno": "4001", "errmsg": "参数缺失"})
        try:
            order = Order.objects.get(id=order_id)
        except Order.DoseNotExsit:
            return http.JsonResponse({"errno": "4001", "errmsg": "订单不存在"})

        if action == 'accept':
            start_date = str(order.begin_date)
            end_date = str(order.end_date)
            ret = check_order(order.house, start_date, end_date)
            if not ret:
                return http.JsonResponse({"errno": "4001", "errmsg": "房屋已被预定"})
            order.status = Order.ORDER_STATUS["WAIT_COMMENT"]
        elif action == 'reject':
            order.status = Order.ORDER_STATUS["REJECTED"]
            order.comment = reason
        else:
            return http.JsonResponse({"errno": "4001", "errmsg": "该操作不存在"})
        order.save()

        return http.JsonResponse({"errno": "0", "errmsg": "操作成功"})


class CommentOrder(LoginRequiredMixin, View):
    # 评论订单("/orders/<int:order_id>/comment", methods=["PUT"])
    def put(self, request, order_id):
        comment = json.loads(request.body.decode()).get('comment')
        user = request.user
        try:
            order = Order.objects.get(id=order_id)
        except:
            return http.JsonResponse({"errno": "4001", "errmsg": "该订单不存在"})
        if not order.user == user:
            return http.JsonResponse({"errno": "4001", "errmsg": "该订单不属于你"})
        order.comment = comment
        order.status = Order.ORDER_STATUS["COMPLETE"]
        order.save()
        order.house.order_count += 1
        order.house.save()
        return http.JsonResponse({"errno": "0", "errmsg": "评论成功"})
